﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Data.Linq.SqlClient;
using System.Web.Security;

public partial class User_ContractsList : System.Web.UI.Page
{
    BankDataDataContext db = new BankDataDataContext();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Roles.IsUserInRole("User"))
        {
            Response.Redirect("~/Account/Login.aspx");
        }
    }

    protected void GridView1_DataBinding(object sender, EventArgs e)
    {
        MembershipUser user = Membership.GetUser();
        var profiles = from profile in db.UserProfiles where profile.userId == (Guid)user.ProviderUserKey select profile;
        SqlDataSourceContracts.SelectParameters["profileId"].DefaultValue = profiles.First().ProfileId.ToString();
    }

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string contractId = GridView1.DataKeys[GridView1.SelectedIndex]["ContractId"].ToString();
        var contracts = from contract in db.Contracts where contract.ContractId == Convert.ToInt32(contractId) select contract;
        Session.Add("contractId", contractId);
        Response.Redirect("~/User/ContractInformation.aspx");
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex != -1)
        {
            decimal payedAmount = 0;
            var contracts = from contract in db.Contracts where contract.ContractId == (int)GridView1.DataKeys[e.Row.RowIndex]["ContractId"] select contract;
            Contract selectedContract = contracts.First();
            var creditCurrencies = from creditCurrency in db.CreditCurrencies
                                   where creditCurrency.CreditId == selectedContract.CreditId &&
                                       creditCurrency.CurrencyId == selectedContract.CurrencyId
                                   select creditCurrency;
            int month = Math.Abs(SqlMethods.DateDiffMonth(DateTime.Now, selectedContract.CreationDate));
            decimal needPayments = selectedContract.Amount * (decimal)(creditCurrencies.First().Percentage / 100 + 1) / selectedContract.TermLength * month;
            foreach (ContractPayment payment in contracts.First().ContractPayments)
            {
                payedAmount += payment.MainAmount;
            }
            if (payedAmount < needPayments)
            {               
                e.Row.Cells[8].Text =  Math.Round(needPayments - payedAmount, 3).ToString();
            }
            else
            {
                e.Row.Cells[8].Text = "0";
            }
        }
    }
}